<template>
    <div class="logic-tree">
        <div v-for="(node, index) in nodes" :key="node.id" class="node-container">
            <div class="node" :ref="setNodeRef(node)">
                <div class="node-slot">
                    <div v-if="!node.dictLogicType" class="node-data">
                        <select-sim v-model="node.data.paramId" :property="'forRiskCheckColumnId'" 
                            :defaultList="[{
                                id: node.data.paramId ?node.data.paramId :'',
                                name:node.data.paramName || ''
                            }]"   
                            :index="index" @save="saveSim1" :placeholder="'风控校验字段'" style="width: 160px;margin-right: 5px; display: flex; align-content: center;" v-if="props.sign==1"/>
                        <select-sim v-model="node.data.paramId" :property="'forIndexParamId'" :forIndexManagementId="props.forIndexManagementId"
                            :defaultList="[{
                                id: node.data.paramId ?node.data.paramId :'',
                                name:node.data.paramName || ''
                            }]"   
                            :index="index" @save="saveSim1" :placeholder="'指标管理参数'" style="width: 160px;margin-right: 5px; display: flex; align-content: center;" v-if="props.sign==2"/>
                        <el-select v-model="node.data.dictOperator" clearable placeholder="操作符" @change="changeOperator(index)" style="width: 110px;margin-right: 5px;">
                            <el-option v-for="item in dictOperatorList" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                        <!-- 操作符是9或者10的时候，可以不用填值，值的框隐藏 -->
                        <div v-if="node.data.dictOperator!='9' && node.data.dictOperator!='10'">
                            <!-- 分为sign==1 前提条件 和 sign==2逻辑条件 -->
                            <div style="display: flex; align-content: center;" v-if="props.sign==1">
                                <!-- 3为字典 4为对象 -->
                                <el-select v-model="node.data.value" clearable placeholder="值" style="width: 160px;" @change="changeDict(index,$event)" v-if="node.data.dictDataPermColumnType=='3'">
                                    <el-option v-for="item in myDictList(node.data.classCode)" :key="item.code" :label="item.name" :value="item.code"/>
                                </el-select>
                                <select-sim v-model="node.data.value" :property="'forPermCommonId'" :forDataPermSourceId="node.data.forDataPermSourceId?node.data.forDataPermSourceId:0"
                                    :defaultList="[{
                                        id: node.data.value ?node.data.value :'',
                                        name:node.data.valueDesc || ''
                                    }]"   
                                    :index="index" @save="saveSim2" :placeholder="'值'" style="width: 160px; display: flex; align-content: center;"  v-else-if="node.data.dictDataPermColumnType=='4'"/>
                                <el-input v-model="node.data.value" placeholder="值" style="width: 160px;" clearable v-else></el-input>
                            </div>
                            <select-sim v-model="node.data.value" :property="'forRiskSourceId'" :riskSourceItem="node.data.riskSourceItem"
                                :defaultList="[{
                                    id: node.data.value ?node.data.value :'',
                                    name:node.data.valueDesc || ''
                                }]"   
                                :index="index" @save="saveSim2" :placeholder="'值'" style="width: 160px;margin-right: 5px; display: flex; align-content: center;" v-if="props.sign==2"/>
                        </div>
                    </div>
                    <div v-if="node.dictLogicType === 'OR'" class="node-or" @click.stop="switchNode(node,'AND')"><el-check-tag checked type="danger">{{ node.data.name }}</el-check-tag></div>
                    <div v-if="node.dictLogicType === 'AND'" class="node-and" @click.stop="switchNode(node,'OR')"><el-check-tag checked type="success">{{ node.data.name }}</el-check-tag></div>
                </div>                
                <div class="btns_group1" v-if="node.grade > 1">
                    <el-button size="small" type="primary" :icon="Plus" circle plain @click.stop="addSiblingNode(node, index)">
                    </el-button>
                    <el-button size="small" type="success" circle plain @click.stop="addChildNode(node, index, 'OR')">
                        <template #icon>
                            <svg-icon name="opSymbol-andOr" width="18px" height="18px"></svg-icon>                                
                        </template>                            
                    </el-button>
                    <el-button size="small" type="danger" :icon="Delete" circle plain @click.stop="deleteNode(node, index)" v-if="!(node.grade==2&&nodes.length==1)"/>
                </div>
            </div>
            <LogicTree v-if="node.children && node.children.length > 0" :nodes="node.children" :sign="props.sign" :forIndexManagementId="props.forIndexManagementId"/>
        </div>
    </div>
</template>
  
<script setup lang="ts">
import { inject } from 'vue';
import { NodeEdit } from './index.vue';
import {Plus,Delete} from '@element-plus/icons-vue'
import type { Dict } from '@/api/pub/type.ts';
import selectSim from '@/components/remoteSelect/simple.vue';
import LogicTree from './logicTreeEdit.vue';

// 生成新的节点ID
function generateNodeId(): number {
    gMaxId.value += 1;
    console.log('id', gMaxId)
    return gMaxId.value;
}
let gMaxId = inject('maxId', ref<number>(0))
// 使用 inject 接收方法
const updateNodeLine:any = inject('updateNodeLine');
const handleUpdateNodeLine = () => {
    if (updateNodeLine) {
        updateNodeLine();
    }
};
// 初始化节点数据
const props = defineProps<{ 
    nodes: NodeEdit[];
    forIndexManagementId?: number;
    sign: number;
}>();
// 增加同级节点
function addSiblingNode(node: NodeEdit, index: number) {

    const newNode: NodeEdit = {
        id: generateNodeId(),
        grade: node.grade,
        dictLogicType: '',   // 节点类型 data、or、and 
        data: {                  // 节点的内容
            "name": `新节点 ${new Date().getTime()}` ,
            "paramId": 0,
            "paramName": "",
            "dictOperator": "",
            "value": "",
            "valueDesc": "",
            "dictDataPermColumnType":"",
            "classCode":"",
            "forDataPermSourceId": 0,
            "riskSourceItem" : null,
        }   
    };

    // 将新节点插入到指定位置
    props.nodes.splice(index + 1, 0, newNode);
    handleUpdateNodeLine();
}
// 增加下级节点,只能为or或者and
function addChildNode(node: NodeEdit, index: number, opType: string) {
    const newNode: NodeEdit = {
        id: generateNodeId(),
        grade: node.grade,
        dictLogicType: opType,   // 节点类型 data、or、and      
        data: { name: opType === 'OR' ? '或' : '且' },
        children: [
            { id: generateNodeId(), grade: node.grade+1,dictLogicType: '', data: { name: `新节点 ${new Date().getTime()}` } },
            { id: generateNodeId(), grade: node.grade+1,dictLogicType: '', data: { name: `新节点 ${new Date().getTime()}` } }
        ]
    };
    // 将新节点插入到指定位置
    props.nodes.splice(index + 1, 0, newNode);
    handleUpdateNodeLine();
}

//删除节点
function deleteNode(_node: NodeEdit, index: number) {

    // 将指定位置数据删除
    props.nodes.splice(index , 1);
    handleUpdateNodeLine();
}
// 切换节点类型
function switchNode(node: NodeEdit, opType: string) {
    node.dictLogicType = opType;
    node.data.name = opType === 'OR' ? '或' : '且';
    // handleUpdateNodeLine();
}
// 创建一个函数来设置 ref
const setNodeRef = (node: NodeEdit) => {
    return (el: any) => {
        node.nodeRef = el;
    };
};
const dictOperatorList = ref<Dict[]>([]);
const dictList = autoDict();
onMounted(() => {
    init();
})
const init = () => {
    dictOperatorList.value = dictList.OPERATOR?.list;
}
const saveSim1 = (msg: any) => {
    props.nodes[msg.index].data.paramId = msg.value?msg.value:null;
    props.nodes[msg.index].data.paramName = msg.item?msg.item.name:null;
    props.nodes[msg.index].data.value = '';
    props.nodes[msg.index].data.valueDesc = '';
    
    if(msg.property =='forRiskCheckColumnId'){
        props.nodes[msg.index].data.dictDataPermColumnType = msg.item?msg.item.dictDataPermColumnType:null;
        props.nodes[msg.index].data.classCode = msg.item?msg.item.dictionary:null;
    }else if(msg.property =='forIndexParamId'){
        props.nodes[msg.index].data.riskSourceItem = msg.item?msg.item:null;
    }
}
const saveSim2 = (msg: any) => {
    props.nodes[msg.index].data.value =  msg.value?msg.value:'';
    props.nodes[msg.index].data.valueDesc = msg.item?msg.item.name:'';
}
const myDictList = (classCode: string|undefined) => {
    if (!classCode) return [];
    // console.log('获取字典下拉：',dictList[classCode]?.list);
    return dictList[classCode]?.list;
}
const changeDict = (index: number, value: string) => {
    if(!value){
        props.nodes[index].data.value = '';
        props.nodes[index].data.valueDesc = '';
        return 
    }
    const selected = myDictList(props.nodes[index].data.classCode).find((item: { code: string; }) => item.code === value);
    props.nodes[index].data.valueDesc = selected.name;
    console.log('选中字典类名：',selected.name);
};
const changeOperator = (index: number) => {
    props.nodes[index].data.value = '';
    props.nodes[index].data.valueDesc = '';
};
</script>
  
<style scoped lang="scss">
.logic-tree {
    display: flex;
    flex-direction: column;
    position: relative;
    gap: 20px;   
    .node-container {
        display: flex;
        align-items: center;
        gap: 40px;
    }

    .node {
        display: flex;
        align-items: center;    
        position: relative;
        height: 40px;
        justify-content: center;
        padding: 0 10px;
        .node-slot{
            height: 40px;
            line-height: 40px;        
            white-space: nowrap;        
            .node-data{
                height: 40px;
                line-height: 40px;
                display: flex;
                align-items: center;
            }
        }
        .btns_group1{            
            display: flex;
            align-items: center;        
            height: 40px;        
            position: absolute;
            left: 0; 
            top: 0;
            opacity: 0; /* 默认不可见 */
            // visibility: hidden;        
            border-radius: 0 4px 4px 0;
            background-color: var(--el-fill-color);        
            .el-button + .el-button {
                margin-left: 10px;
            }
        }   
    }
    :deep(.el-icon){
        height: 2em;
        width: 2em;
        line-height: 2em;
    }
    .node:hover {
        border-radius: 4px 0 0 4px;
        background-color: var(--el-fill-color);
        z-index: 1;
        cursor: pointer;
        .btns_group1{     
            // visibility: visible;
            left: 100%; 
            width: 102px;
            opacity: 1; /* 可见 */
        }
    } 
}
</style>
